package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.constants.Constants;
import com.easychat.entity.dto.MessageSendDTO;
import com.easychat.entity.dto.SysSettingDTO;
import com.easychat.entity.dto.TokenUserInfoDTO;
import com.easychat.entity.po.UserInfo;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.entity.vo.UserInfoVO;
import com.easychat.exception.BusinessException;
import com.easychat.redis.RedisComponent;
import com.easychat.service.UserInfoService;
import com.easychat.websocket.MessageHandler;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.FrameworkServlet;

import javax.annotation.Resource;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController("accountController")
@RequestMapping("/account")
@Validated
//@Slf4j
public class AccountController extends ABaseController{

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private RedisComponent redisComponent;
    @Resource
    private MessageHandler messageHandler;


    /**
     * 获取验证码并存入redis
     * @return
     */
    @RequestMapping("/checkCode")
    public ResponseVO checkCode() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100,42);//图片验证码，高，宽
        String code = captcha.text();
        //log.info("验证码是：{}", code);//验证码结果
        String codeBase64 = captcha.toBase64();
        String checkCodeKey = UUID.randomUUID().toString();
        //将验证码结果存入redis，为了区分不同验证码，redis中的key使用UUID作为后缀，避免重复
        redisTemplate.opsForValue().set(Constants.REDIS_KEY_CHECK_CODE+checkCodeKey,code,Constants.REDIS_TIME_1MIN*10, TimeUnit.SECONDS);
        //向客户端返回结果：验证码图片 + 唯一标识验证码key
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("checkCode", codeBase64);//可转为图片，表示验证码图片
        resultMap.put("checkCodeKey", checkCodeKey);
        return getSuccessResponseVO(resultMap);
    }

    /**
     * 注册
     * @param checkCodeKey 验证码key
     * @param email 邮箱
     * @param password 密码
     * @param nickName 昵称
     * @param checkCode 验证码
     * @return
     */
    @RequestMapping("/register")
    public ResponseVO register(
            @NotEmpty String checkCodeKey,
            @NotEmpty @Email String email,
            @NotEmpty String password,
            @NotEmpty String nickName,
            @NotEmpty String checkCode) {
        try {
            //取出redis中checkCodeKey对应的验证码，与前端传过来的对比
            if (!checkCode.equalsIgnoreCase((String) redisTemplate.opsForValue().get(Constants.REDIS_KEY_CHECK_CODE + checkCodeKey))) {
                //验证码错误
                throw new BusinessException("图片验证码错误");
            }
            userInfoService.register(email, password, nickName);
            return getSuccessResponseVO(null);
        } finally {
            //删除验证码
            redisTemplate.delete(Constants.REDIS_KEY_CHECK_CODE + checkCodeKey);
        }
    }

    /**
     * 登录
     * @param checkCodeKey 验证码key
     * @param email 邮箱
     * @param password 密码
     * @param checkCode 验证码
     * @return
     */
    @RequestMapping("/login")
    public ResponseVO<UserInfoVO> login(
            @NotEmpty String checkCodeKey,
            @NotEmpty @Email String email,
            @NotEmpty String password,
            @NotEmpty String checkCode) {
        try {
            //取出redis中checkCodeKey对应的验证码，与前端传过来的对比
            if (!checkCode.equalsIgnoreCase((String) redisTemplate.opsForValue().get(Constants.REDIS_KEY_CHECK_CODE + checkCodeKey))) {
                //验证码错误
                throw new BusinessException("图片验证码错误");
            }
            TokenUserInfoDTO tokenUserInfoDTO = userInfoService.login(email, password);
            //组装返回给前端的数组
            UserInfoVO userInfoVO = new UserInfoVO();
            UserInfo userInfo = userInfoService.getUserInfoByUserId(tokenUserInfoDTO.getUserId());
            BeanUtils.copyProperties(userInfo, userInfoVO);//公共属性拷贝
            userInfoVO.setToken(tokenUserInfoDTO.getToken());
            userInfoVO.setAdmin(tokenUserInfoDTO.getAdmin());
            return getSuccessResponseVO(userInfoVO);
        } finally {
            //删除验证码
            redisTemplate.delete(Constants.REDIS_KEY_CHECK_CODE + checkCodeKey);
        }
    }

    /**
     * 获取系统设置
     * @return
     */
    @RequestMapping("/getSysSetting")
    @GlobalInterceptor
    public ResponseVO<SysSettingDTO> getSysSetting() {
        return getSuccessResponseVO(redisComponent.getSysSetting());
    }

    /**
     * 测试redisson发布订阅
     * @return
     */
    @RequestMapping("/test")
    public ResponseVO test() {
        MessageSendDTO messageSendDTO = new MessageSendDTO();
        messageSendDTO.setMessageContent("redisson测试---" + System.currentTimeMillis());
        messageHandler.sendMessage(messageSendDTO);
        return getSuccessResponseVO(null);
    }
}
